package com.bicap.cloud.nettyserver;

import com.bicap.cloud.nettyserver.config.NettyConfig;
import com.bicap.cloud.nettyserver.config.NettyServer;
import io.netty.channel.ChannelFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.net.InetSocketAddress;

@SpringBootApplication
public class NettyServerApplication implements CommandLineRunner {

	@Autowired
	private NettyServer nettyServer;

	@Autowired
	private NettyConfig nettyConfig;

	public static void main(String[] args) {
		SpringApplication.run(NettyServerApplication.class, args);
	}

	@Bean
	public NettyServer chatServer() {
		return new NettyServer();
	}

	@Override
	public void run(String... args) throws Exception {

		/***
         * 绑定端口并启动去接收进来的连接
         */
		InetSocketAddress address = new InetSocketAddress(nettyConfig.getHost(), nettyConfig.getPort());
		ChannelFuture future = nettyServer.start(address);

		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				nettyServer.destroy();
			}
		});
		/**
         * 这里会一直等待，直到socket被关闭
         */
		future.channel().closeFuture().syncUninterruptibly();
	}
}
